package com.netsdk.demo.module;

import com.netsdk.config.AqieConfig;
import com.netsdk.lib.NetSDKLib;
import com.netsdk.lib.NetSDKLib.fMessCallBack;
import com.netsdk.lib.ToolKits;
import com.netsdk.utils.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * \if ENGLISH_LANG
 * alarm listen interface
 * contains: start and stop alarm listen
 * \else
 * 报警接口实现
 * 包含 ：向设备订阅报警和停止订阅报警
 * \endif
 */
@Slf4j
@Component
public class AlarmListenModule {

	public static Map<String, Boolean> listenMap = new HashMap<>();

	@PostConstruct
	void init() {
		AqieConfig bean = SpringUtils.getBean(AqieConfig.class);
		bean.getDevices().forEach(device -> {
			listenMap.put(device.getId(), false);
		});
	}

	
	/**
	 * \if ENGLISH_LANG
	 * start alarm listen
	 * \else
	 * 向设备订阅报警
	 * \endif
	 */
	public static boolean startListen(fMessCallBack cbMessage, String deviceNo) {
		Boolean bListening = listenMap.get(deviceNo);
		if (bListening) {
			log.info("Had Subscribe Alarm.");
			return true;
		}
		
		LoginModule.netsdk.CLIENT_SetDVRMessCallBack(cbMessage, null); // set alarm listen callback
		NetSDKLib.LLong m_hLoginHandle = LoginModule.handlerMaps.get(deviceNo);
		bListening = LoginModule.netsdk.CLIENT_StartListenEx(m_hLoginHandle);
		if (!bListening) {
			log.info("CLIENT_StartListenEx Failed! {}", ToolKits.getErrorCodePrint());
			return false;
		} else { 
			log.info("CLIENT_StartListenEx success. {} {}", m_hLoginHandle, deviceNo);
		}

		listenMap.put(deviceNo, true);
		return true;
	}
	
	/**
	 * \if ENGLISH_LANG
	 * stop alarm listen
	 * \else
	 * 停止订阅报警
	 * \endif
	 */
	public static boolean stopListen(String deviceNo) {
		Boolean bListening = listenMap.get(deviceNo);
		if (!bListening) {
			return true;
		}
		NetSDKLib.LLong m_hLoginHandle = LoginModule.handlerMaps.get(deviceNo);
	   	if (!LoginModule.netsdk.CLIENT_StopListen(m_hLoginHandle)) {
			log.info("CLIENT_StopListen Failed!" + ToolKits.getErrorCodePrint());
			return false;
		} else { 
			log.info("CLIENT_StopListen success. {} {}", m_hLoginHandle, deviceNo);
		}

		listenMap.put(deviceNo, false);
		return true;
	}

}
	



